﻿using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PropertyChanged;
using JGMelLib;
using GalaSoft.MvvmLight.CommandWpf;
using System.ComponentModel;
using System.Collections;
using System.Collections.ObjectModel;
using JGMelLib.Models;
using PropertyChanged;
using Xceed.Wpf.Toolkit;
using System.Configuration;
using S7.Net;
using GalaSoft.MvvmLight.Messaging;
using Comm;
using System.Data.SqlTypes;

namespace Kinlo.UI.Main.VM
{
    public class MesSettingVM:ViewModelBase
    {
        public string WorkNo { get; set; }
        public string DeviceNo { get; set; }
        public string UserNo { get; set; }
        public string CurrentBillNo { get; set; }

        public ObservableCollection<RespData> WorkNoLists { get; set; } = new ObservableCollection<RespData>();
        public RespData WorkNoSelectedItem { get; set; }
        private int DBNo;
        private string ipaddr = "192.168.10.100";
        Plc plc;
        object locker = new object();
        public MesSettingVM()
        {
            try
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["DBNo2"], out DBNo))
                {
                    DBNo = 42;
                }

                WorkNo = ConfigurationManager.AppSettings["WorkNo"];
                DeviceNo = ConfigurationManager.AppSettings["EquNo"];
                var addr = ConfigurationManager.AppSettings["Ipaddr"];
                UserNo = GlobalValues.UserNo;
                CurrentBillNo = GlobalValues.BillNo; 

                if (!string.IsNullOrEmpty(addr))
                {
                    ipaddr = addr;
                }
                plc = new Plc(CpuType.S71500, ipaddr, 0, 0);
                plc.Open();
            }
            catch (Exception ex)
            {
                Logger.Info($"工单下发生异常 {ex}");
            }
        }

        public void GetWorkNoList()
        {
          var rsp= MesHelper.GetWorkNoList(WorkNo,DeviceNo);
            if (rsp!=null&&rsp.success && rsp.resultData != null)
            {
                WorkNoLists = new ObservableCollection<RespData>(rsp.resultData);
                WorkNoSelectedItem = WorkNoLists.FirstOrDefault();
            }
            else
            {
                MessageBox.Show("获取工单号失败", "错误");
            }
        }
        RelayCommand cmdGetWorkNo;
        public RelayCommand CmdGetWorkNo
        {
            get { return cmdGetWorkNo ?? (cmdGetWorkNo = new RelayCommand(() => DoCmdGetWorkNo())); }
        }
        void DoCmdGetWorkNo()
        {
            //try
            //{
            //    int clearInt = 0;
            //    //投入
            //    plc.Write(DataType.DataBlock, 42, 688, clearInt);
            //    //产出
            //    plc.Write(DataType.DataBlock, 42, 692, clearInt);
            //    //合格
            //    plc.Write(DataType.DataBlock, 42, 696, clearInt);
            //    //不合格
            //    plc.Write(DataType.DataBlock, 42, 700, clearInt);
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("清除产量失败，请先点击连接PLC！！！");
            //}


            GetWorkNoList();
        }


        RelayCommand cmdSendWorkNo;
        public RelayCommand CmdSendWorkNo
        {
            get { return cmdSendWorkNo ?? (cmdSendWorkNo = new RelayCommand(() => DoCmdSendWorkNo())); }
        }
        void DoCmdSendWorkNo()
        {
            try
            {
                //WorkNoSelectedItem = new RespData();
                //WorkNoSelectedItem.Bill_No = "SF23122901101";
                //UserNo = "000164";

                if (WorkNoSelectedItem == null || string.IsNullOrEmpty(WorkNoSelectedItem.Bill_No)|| string.IsNullOrEmpty(UserNo) )
                {
                    MessageBox.Show("操作员或工单号不能为空,", "错误");
                    return;
                }

                GlobalValues.BatchNo = WorkNoSelectedItem.PC_No;
                GlobalValues.UserNo = UserNo;
              CurrentBillNo= GlobalValues.BillNo = WorkNoSelectedItem.Bill_No;
                var strBytes = GetStringBytes(WorkNoSelectedItem.Bill_No);
                var userBytes = GetStringBytes(UserNo);
                byte[] emptyBytes = new byte[40]; // 创建一个长度为40的空字节数组
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 4, emptyBytes);  // 先清空地址

                    plc.Write(DataType.DataBlock, DBNo, 260, strBytes);
                    plc.Write(DataType.DataBlock, DBNo, 4, userBytes);
                }
                Logger.Info($"工单号下发完成 {WorkNoSelectedItem.Bill_No} {UserNo}");
                MessageBox.Show($"工单号下发完成 {WorkNoSelectedItem.Bill_No} {UserNo}", "信息");


                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (config.AppSettings.Settings.AllKeys.Contains("UserNo"))
                {
                    config.AppSettings.Settings["UserNo"].Value = UserNo;
                }
                else
                {
                    config.AppSettings.Settings.Add("UserNo", UserNo);
                } 
                if (config.AppSettings.Settings.AllKeys.Contains("BillNo"))
                {
                    config.AppSettings.Settings["BillNo"].Value = GlobalValues.BatchNo;
                }
                else
                {
                    config.AppSettings.Settings.Add("BillNo", GlobalValues.BatchNo);
                }

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings"); 

            }
            catch (Exception ex)
            {
                Logger.Info($"下发工单发生异常 {ex}");
            } 
        }

        byte[] GetStringBytes(string s)
        {
            if (s.Length > 20)
                s = s.Substring(0, 20);
            var s1 = new byte[] { 0x30 };
            var s2 = new byte[] { (byte)s.Length };
            var s3 = Encoding.Default.GetBytes(s);
            var s4 = s1.Concat(s2).Concat(s3).ToArray();
            return s4;
        }
         
    }
}
